package com.yuan.zs.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.cloud.media.player.BDCloudMediaPlayer;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.BaseUserManager;
import com.yuan.base.framework.bean.UserInfo;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.utils.FileUtil;
import com.yuan.zs.AppContext;
import com.yuan.zs.Constant;
import com.yuan.zs.R;
import com.yuan.zs.Urls;
import com.yuan.zs.bean.Child;
import com.yuan.zs.bean.Notice;
import com.yuan.zs.common.CacheManager;
import com.yuan.zs.ui.account.ApplyParentBindingActivity;
import com.yuan.zs.ui.wonderful.MainWonderfulFragment;

import java.util.List;

public class MainActivity extends BaseFrameworkActivity {

	private MainSchoolFragment mainSchoolFragment;
	private MainVideoFragment mainVideoFragment;
	private MainWonderfulFragment mainWonderfulFragment;
	private MainMyFragment mainMyFragment;
	// 当前显示的fragment的index
	private int currentTabIndex = 0;
	private Fragment[] fragments;
	private TextView[] mTabs;

	private long mExitTime;// 退出时间
	private static final int INTERVAL = 2000;// 退出间隔

	@Override
	protected int getLayoutId() {
		return R.layout.activity_main;
	}

	@Override
	protected void bindViews() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加禁止系统扫描图片的文件
		FileUtil.createFile(AppContext.getSavePath() + "/.nomedia");
		BDCloudMediaPlayer.setAK(Constant.BDAK);
		getUserInfo();
	}

	private void getUserInfo() {
		BaseHttpRequest.get(Urls.getUrl(Urls.getParentInfo), new BaseHttpCallBack<UserInfo>() {

			@Override
			public void onPreStart() {
				showProgressBar("正在获取信息...");
			}

			@Override
			public void onSuccess(UserInfo result) {
				// 用户存在则表示已认证通过，否则去申请认证
				if (result == null) {
					Intent intent = new Intent(MainActivity.this, ApplyParentBindingActivity.class);
					startActivity(intent);
				} else {
					BaseUserManager.saveUserInfo(result);
					getChild();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				super.onFailure(code, msg);
				Intent intent = new Intent(MainActivity.this, LoginActivity.class);
				startActivity(intent);
				closeSelf();
			}
		});
	}

	private void getChild() {
		BaseHttpRequest.get(Urls.getUrl(Urls.getChildList), new BaseHttpCallBack<List<Child>>() {
			@Override
			public void onPost() {
				hideProgressBarAtOnce();
			}

			@Override
			public void onSuccess(List<Child> result) {
				if (result != null) {
					CacheManager.getInstance().saveChild(result);
					// 必须获取个人数据和孩子数据
					initTab();
				} else {
					showToast("数据获取失败，请重新登录");
					AppContext.getInstance().logout();
					Intent intent = new Intent(MainActivity.this, LoginActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					closeSelf();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
			}
		});
	}

	private void getNotificationData() {
		CacheManager.getInstance().initNotificationData(new CacheManager.HandleCallback<List<Notice>>() {
			@Override
			public void onCacheSuccess(List<Notice> result) {
			}

			@Override
			public void onHttpSuccess(List<Notice> result) {
			}

			@Override
			public void onError() {
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
//		AppUpdate.getInstance().cancel();//释放检查更新的下载
	}

	/**
	 * 初始化tab页
	 */
	private void initTab() {
		mTabs = new TextView[]{findViewById(R.id.tab_1), findViewById(R.id.tab_2), findViewById(R.id.tab_3), findViewById(R.id.tab_4)};
		// 把第一个tab设为选中状态
		mTabs[currentTabIndex].setSelected(true);
		mainSchoolFragment = new MainSchoolFragment();
		mainVideoFragment = new MainVideoFragment();
		mainWonderfulFragment = new MainWonderfulFragment();
		mainMyFragment = new MainMyFragment();
		fragments = new Fragment[]{mainSchoolFragment, mainVideoFragment, mainWonderfulFragment, mainMyFragment};
		getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragments[currentTabIndex]).show(fragments[currentTabIndex]).commit();

		getNotificationData();
	}

	/**
	 * tab点击事件
	 */
	public void onTabClicked(View view) {
		int index = Integer.parseInt(view.getTag().toString()) - 1;
		if (currentTabIndex != index) {
			FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
			trx.hide(fragments[currentTabIndex]);
			if (!fragments[index].isAdded()) {
				trx.add(R.id.fragment_container, fragments[index]);
			}
			trx.show(fragments[index]).commit();
		} else {
			return;
		}
		mTabs[currentTabIndex].setSelected(false);
		// 把当前tab设为选中状态
		mTabs[index].setSelected(true);
		currentTabIndex = index;
	}

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - mExitTime > INTERVAL) {
			Toast.makeText(this, "再按一次返回键,可直接退出程序", Toast.LENGTH_SHORT).show();
			mExitTime = System.currentTimeMillis();
		} else {
			closeSelf();
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
			// moveTaskToBack(true);// 进入后台。
		}
	}

	/**
	 * activityResult传递事件,用于传递给fragment
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
}
